<template>
  <el-card>
    <div slot="header">
      <h3>开发计划详情-编辑</h3>
    </div>
    <div class="page-body">
      <DevelopPlanForm
        ref="formRef"
        :data-source.sync="formData"
        :category-path-set="categoryPathSet"
        :user-options="userInfoOptions"
      />
      <el-divider content-position="left">开发需求明细</el-divider>
      <el-row>
        <skus-table
          ref="skusTable"
          showActionCol
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          :actionRender="renderTableBtnAction"
        >
          <el-row slot="content_context" type="flex" justify="space-between">
            <BtnRender :render="renderBtnsBar" />
            <div>
              <span v-if="formData.totalOrderFrequency || formData.totalOrderAmount ">合计：</span>
              <span v-if="formData.totalOrderFrequency">{{ formData.totalOrderFrequency }}次</span>
              <span v-if="formData.totalOrderAmount">{{ formData.totalOrderAmount }}元</span>
            </div>
          </el-row>
        </skus-table>
      </el-row>
      <FooterFields :fieldsItems="fieldsItems" :fieldsData="fieldsData" />
    </div>
    <AddRequirementDialog
      :visible.sync="dialogVisible"
      @getDetailNos="updateRequirementList"
    />
    <ViewProductDetailsDialog
      :visible.sync="viewProductDetails.visible"
      :req-detail-no="viewProductDetails.reqDetailNo"
    />
   </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import FooterFields from '@/pages/commodity/components/FooterFields/DataRender';
import AddRequirementDialog from '../components/AddRequirementsDialog';
import DevelopPlanForm from '../components/DevelopPlanForm';
import ViewProductDetailsDialog from '../components/ViewProductDetailsDialog';
import { EDIT_TABLE_COLUMNS, FIELDS_ITEMS, getSkuCountCol } from './constants/actionPage';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { TableInfo } from '@/utils/getUtils';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  getReqDetailListByReqDetailNosService,
  getDevPlanEditInfoService,
  resubmitService
} from '@/api/commodity/developmentRequirementPlan/developPlan';
export default {
  components: {
    SkusTable,
    BtnRender,
    FooterFields,
    AddRequirementDialog,
    DevelopPlanForm,
    ViewProductDetailsDialog
  },
  data () {
    return {
      initData: {}, // 初始化数据，用来和表格表单数据进行比对
      formData: {},
      formRules: {
        devAreaId: [{ required: true, trigger: 'change', message: '开发区域不能为空' }],
        developerId: [{ required: true, trigger: 'change', message: '开发人不能为空' }],
        devDeptName: [{ required: true, trigger: 'change', message: '开发部门不能为空' }],
        devPlanTime: [{ required: true, trigger: 'change', message: '开发计划时间不能为空' }],
        note: [{ required: true, trigger: 'change', message: '开发计划说明不能为空' }],
      },
      TableInfo: new TableInfo({ columns: EDIT_TABLE_COLUMNS, dimensionKey: 'reqDetailNo' }),
      fieldsItems: FIELDS_ITEMS,
      fieldsData: {},
      pickerOptions: {
        disabledDate: time => time.getTime() < new Date().getTime() - 8.64e7 // 当前日期之前的不可选择
      },
      dialogVisible: false,
      loadingInstance: {
        submitBtn: false,
        userSelect: false
      },
      categoryPathSet: [], // categoryPath集合
      userInfoOptions: [],
      planNo: '', // 单据号
      viewProductDetails: {
        visible: false,
        reqDetailNo: ''
      }
    }
  },
  mounted () {
    this.TableInfo.setColumns([
      ...EDIT_TABLE_COLUMNS,
      getSkuCountCol(this.handleViewDetails)
    ])
    this.planNo = this.$route?.query?.planNo
    this.loadDevPlanInfo()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnBars = [
        { label: '新增需求', method: this.handleAddRequirement },
        {
          label: '一键清空',
          type: 'default',
          method: this.handleClearAll,
          disabled: this.TableInfo.isNullList()
        },
        {
          label: '提交计划',
          method: this.handleSubmitPlan,
          loading: this.loadingInstance.submitBtn,
          disabled: this.TableInfo.isNullList()
        },
        { label: '返回', type: 'default', method: this.handleGoBack }
      ]
      return getListPageBtnsBar(h, btnBars, null, 'start')
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '删除', method: this.handleDelete }]
      return getTableAction({ h, row, actionList })
    },
    // 新增需求
    handleAddRequirement () {
      this.dialogVisible = true
    },
    // 删除
    handleDelete (row) {
      this.TableInfo.removeList(row)
    },
    // 提交计划
    handleSubmitPlan () {
      const alertMessage = () => { this.$message.warning('必填项不能为空！') }
      this.$refs?.formRef?.$refs?.formData.validate(valid => {
        valid ? this.fetchSubmitPlan() : alertMessage()
      })
    },
    // 一键清空
    handleClearAll () {
      const content = '确定后将清空所有需求，您确认吗？'
      this.$confirm(content, '清空', {
        type: 'warning',
      }).then(() => {
        this.TableInfo.clearList()
      }).catch(() => {})
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'developPlanList' })
    },
    // 加载开发详情
    async loadDevPlanInfo () {
      const data = { planNo: this.planNo }
      const res = await getDevPlanEditInfoService(data, '.page-body')
      if (res?.retData) {
        this.initData = _.cloneDeep(res.retData)
        this.TableInfo.setList(res.retData.detailVoList)
        this.setFormDataDetails(res.retData)
        this.fieldsData = res.retData
      }
    },
    // 设置表单详情数据
    setFormDataDetails (retData) {
      const { categoryPathSet, startTime, endTime, developerId, developerName } = retData
      this.formData = {
        ..._.pick(retData,
        [
          'categoryPath', 'brandName', 'devAreaName', 'devAreaId', 'planName',
          'developerName', 'developerId', 'devDeptName', 'devDeptNo', 'note'
        ]),
        devPlanTime: [startTime, endTime]
      }
      this.categoryPathSet = categoryPathSet
      this.userInfoOptions = developerId ? [{ userId: developerId, userName: developerName }] : []
    },
    // 更新需求列表
    async updateRequirementList (nos) {
      const reqDetailNos = [...new Set([...this.TableInfo.getListAttrs(), ...nos])]
      if (reqDetailNos.length == 0) return
      const data = reqDetailNos
      const res = await getReqDetailListByReqDetailNosService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(res.retData)
        this.categoryPathSet = [...new Set([...res.retData.map(item => item.categoryPath)])]
        this.formData.categoryPath = this.categoryPathSet.join(',')
        const brandNames = [...new Set([...res.retData.map(item => item.brandName)])]
        this.formData.brandName = brandNames.join(',')
      }
    },
    // 提交请求
    async fetchSubmitPlan () {
      const formDetails = this.$refs?.formRef?.getFormDetails() ?? {}
      const data = {
        ...formDetails,
        reqDetailNos: this.TableInfo.getListAttrs(),
        planNo: this.planNo
      }
      const loadingFn = state => { this.loadingInstance.submitBtn = state }
      const res = await resubmitService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
    },
    // 查看商品详情
    handleViewDetails (row) {
      this.viewProductDetails.visible = true
      this.viewProductDetails.reqDetailNo = row.reqDetailNo
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-divider__text {
  left: 0;
  padding-left: 0;
}
.percent-width {
  width: 100%;
}
.category-path-content {
  width: 100%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.category-path-list {
  height: 200px;
  overflow: hidden;
  overflow-y: auto;
  li {
    padding: 5px 0;
    border-bottom: 1px dashed #ccc;
  }
}
</style>
